from baseview import BaseView
from ..devicetree import DeviceTree
from ..bases import widgets, tree
from .. import editors


class DeviceView(BaseView):
    topwidget_name = 'Devices'
    topwidget_cls = widgets.HPane
    def __init__(self, **kwargs):
        self.topwidget = widgets.HBox()
        super(DeviceView, self).__init__(**kwargs)
        self.DeviceSystem = self.MainController.DeviceSystem
        self.current_device = None
        self.device_editor = None
        
        names = ['id', 'Number', 'Name', 'Universe', 'Start Chan']
        attrs = ['id', 'device_num', 'name', 'universe_id', 'start_chan']
        types = [str, int, str, str, int]
        objnames = ['PatchedDevice']
        attrmap = {}
        for key, attr in zip(names, attrs):
            attrmap[key] = {}
            for objkey in objnames:
                attrmap[key][objkey] = attr
        t_kwargs = dict(column_names=names, column_types=types, column_attr_map=attrmap, 
                        obj_name_attr='saved_class_name', child_name_attr='dont_add_children', 
                        base_dict=self.DeviceSystem.PatchedDevices, show_dicts=False)
        self.device_tree = tree.GenericTreeStore(**t_kwargs)
        
        col = [1, 2, 3, 4]
        colmap = dict(zip(col, [names[i] for i in col]))
        self.device_tree_widget = widgets.Tree(name='Devices', model=self.device_tree, 
                                               columns=colmap)
        self.device_tree_widget.connect('selection_changed', self.on_device_tree_selection_changed)
        self.topcontainer.pack_start(self.device_tree_widget.topwidget, expand=True)
        
        self.topwidget.show_all()
        
        self.DeviceSystem.connect('new_device', self.on_ds_new_device)
    
    def unlink(self):
        super(DeviceView, self).unlink()
        self.DeviceSystem.disconnect(callback=self.on_ds_new_device)
    
    def set_current_device(self, device):
        if self.device_editor:
            self.remove_editor(self.device_editor)
        self.add_editor(editors.PatchedDeviceEditor, 'device_editor', device=device)
        self.topcontainer.pack_start(self.device_editor.topwidget)
    
    def on_ds_new_device(self, **kwargs):
        if kwargs.get('base') == 'PatchedDevice':
            self.device_tree.refresh_all()
            
    def on_device_tree_selection_changed(self, **kwargs):
        device = self.device_tree_widget.selected_obj
        if device and device != self.current_device:
            self.set_current_device(device)
